using System;
using System.Collections.Generic;
using System.Linq;
using Azure.Domain.Models;
using Rhino.Mocks;
using Xunit;

namespace Azure.Tests.Domain.ServiceFacts
{
    public class LoadFacts : ServiceFactBase
    {
        private Post _post = Test.Post;

        [Fact]
        public void LoadPostChecksCacheFistToRetrieveAnItem()
        {
            Cache.Expect(x => x.Get(_post.PartitionKey, _post.RowKey)).Return(_post);

            _post = ClassUnderTest.LoadPost(_post.PartitionKey, _post.RowKey);

            Assert.NotNull(_post);
            Cache.VerifyAllExpectations();
        }

        [Fact]
        public void LoadPostWillCheckTheRepositoryIfTheCacheDoesNotHaveIt()
        {
            Repository.Expect(x => x.Load(_post.PartitionKey, _post.RowKey)).Return(_post);

            _post = ClassUnderTest.LoadPost(_post.PartitionKey, _post.RowKey);

            Assert.NotNull(_post);
            Cache.VerifyAllExpectations();
        }

        [Fact]
        public void LoadWillRetrieveByPartitionKeyAndRowKeyWhenUsingUriFormat()
        {
            Repository.Stub(x => x.Query(Arg<IQueryable<Post>>.Is.Anything)).Return(new List<Post> {_post});

            Post result = ClassUnderTest.LoadPost(_post.Year(), _post.Month(), _post.Day(), _post.Slug);

            Assert.NotNull(result);
        }

        [Fact]
        public void LoadWillPutTheItemInCacheIfItWasRetrievedFromTheRepository()
        {
            Repository.Expect(x => x.Load(_post.PartitionKey, _post.RowKey)).Return(_post);

            _post = ClassUnderTest.LoadPost(_post.PartitionKey, _post.RowKey);

            Assert.NotNull(_post);
            Cache.AssertWasCalled(
                x => x.Add(Arg<Post>.Matches(y => y.PartitionKey == _post.PartitionKey && y.RowKey == _post.RowKey)));
        }
    }
}